#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    long long minimumRemoval(vector<int>& beans) {
        int n = beans.size();
        vector<long long> s(n + 1);
        sort(beans.begin(), beans.end());
        for (int i = 1; i <= n; i++) {
            s[i] = s[i - 1] + beans[i - 1];
        }
        long long ans = 1e18;
        for (int i = 0; i < n; i++) {
            if (i == 0) {
                ans = min(ans, s[n] - (long long)(n - i) * beans[i]);
                continue;
            }
            int l = -1;
            int r = i;
            int x = beans[i];
            while (l + 1 != r) {
                int mid = (l + r) >> 1;
                if (beans[mid] >= x)r = mid;
                else l = mid;
            }

            ans = min(ans, s[l + 1] + (s[n] - s[i + 1] - (long long)(n - i - 1) * beans[i]));

        }
        return ans;
    }
};